#include "player.h"
#include "menudialog.h"

//#include <QNetworkReply>
//#include <QLayout>
//#include <QKeyEvent>
//#include <QTimer>
#include <QFile>
//#include <QLabel>
#include <QWebPage>
#include <QWebView>
#include <QWebFrame>
#include <QDebug>

#define HTTP_BUFFER_SIZE (512 * 1024) // 512 kB
#define HTTP_BUFFER_MIN (512  * 1024) // 10 kB

class PlayerPrivate {
public:
    PlayerPrivate():
            page(0),
            view(0)
    {}
public:
    QWebPage* page;
    QWebView* view;
};

Player::Player(QObject* parent) :
    QObject(parent),
    d(new PlayerPrivate)
{
    d->page = new QWebPage(this);
    d->page->settings()->setAttribute(QWebSettings::PluginsEnabled, true);

    QFile html(":/web/player.html");
    html.open(QIODevice::ReadOnly);
    d->page->mainFrame()->setHtml(html.readAll());
}

Player::~Player()
{
    delete d;
}

void Player::connectAuthenticator(QObject* receiver, const char* method)
{
    connect(d->page->networkAccessManager(),
            SIGNAL(authenticationRequired(QNetworkReply*, QAuthenticator*)),
            receiver, method);
}

bool Player::canPlay(const QString& mimeType)
{
    qDebug() << "Request for " << mimeType;
    return mimeType == "video/x-flv"
        || mimeType == "video/mp4";
}

void Player::play(const QUrl& url)
{
    qDebug() << "PLAYING " << url.toString();

    QString cmd("document.getElementById('player').sendEvent('LOAD', '%0');");
    d->page->mainFrame()->evaluateJavaScript(cmd.arg(url.toString()));
}

void Player::pause()
{
    d->page->mainFrame()->evaluateJavaScript(
            "document.getElementById('player').sendEvent('PLAY');"
    );
}

void Player::stop()
{
    d->page->mainFrame()->evaluateJavaScript(
            "document.getElementById('player').sendEvent('STOP');"
    );
}

QWidget* Player::widget() const
{
    if (!d->view) {
        d->view = new QWebView;
        d->view->setPage(d->page);
    }
    return d->view;
}

/*void Player::showPlaybackMenu()
{
    MenuDialog menu(this);
    menu.addActionItem(tr("Stop"), source, SLOT(stop()));
    menu.exec();
}*/
